﻿using Mobileterminal.Common;
using Mobileterminal.Dtos;
using Mysqlx.Session;
using MySqlX.XDevAPI.Common;
using Newtonsoft.Json;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace Mobileterminal.Forms
{
    public partial class QuerySterilizationForm : UIPage
    {
        public QuerySterilizationForm()
        {
            InitializeComponent();  //初始化控件

            LoadDataAsync();  //器械显示

            LoadTreeDataAsync();


        }




        /// <summary>
        /// 器械显示
        /// </summary>
        /// <returns></returns>
        private async Task LoadDataAsync(string apparatusNo = null, string apparatusName = null)
        {
            // 构建动态查询参数
            var queryParams = new List<string>();
            if (!string.IsNullOrEmpty(apparatusNo))
                queryParams.Add($"ApparatusNo={Uri.EscapeDataString(apparatusNo)}");
            if (!string.IsNullOrEmpty(apparatusName))
                queryParams.Add($"ApparatusName={Uri.EscapeDataString(apparatusName)}");

            var url = "https://localhost:7224/api/Apparatus/QueryApparatus";
            if (queryParams.Count > 0)
                url += "?" + string.Join("&", queryParams);
            var json = await HttpClientHelper.ClientAsync("GET", url);
            var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Result<List<ApparatusDto>>>(json);
            if (result.Code == 200)
            {
                result.Data = result.Data.OrderByDescending(x => x.ApparatusId).ToList();
                foreach (var item in result.Data)
                {
                    item.StateName = item.State == false ? "停用" : "启用";
                }
                uiDataGridView1.DataSource = result.Data;


            }
        }

        //图片显示处理
        private void demoGrid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {

            if (uiDataGridView1.Columns[e.ColumnIndex].Name.Equals("apparatusImg"))
            {
                var path = this.uiDataGridView1.Rows[e.RowIndex].Cells["apparatusImg"].Value?.ToString() ?? "";
                //string path = System.Windows.Forms.Application.StartupPath + @"/1.gif";
                if (!string.IsNullOrEmpty(path))
                {

                    e.Value = Image.FromStream(System.Net.WebRequest.Create(path).GetResponse().GetResponseStream());
                }
                else {
                    e.Value = global::Mobileterminal.Properties.Resources.Tom;
                }
                //e.Value = GetImage(path);
            }
        }

        public System.Drawing.Image GetImage(string path)
        {
            System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open);
            System.Drawing.Image result = System.Drawing.Image.FromStream(fs);
            fs.Close();
            return result;

        }


        /// <summary>
        /// 树形控件样式​
        /// </summary>
        private void ConfigureTreeView()
        {
            // 初始化图片列表
            var imageList = new ImageList
            {
                ImageSize = new Size(24, 24)
            };


            uiTreeView1.ImageList = imageList;
            uiTreeView1.ItemHeight = 32;
            uiTreeView1.ShowLines = true;
            uiTreeView1.LineColor = Color.Silver;
        }


        /// <summary>
        /// / 树形结构转换方法
        /// </summary>
        public static class TreeConverter
        {
            public static List<ApparatusTypeDTO> BuildTree(List<ApparatusTypeDTO> source)
            {
                var nodeMap = new Dictionary<int, ApparatusTypeDTO>();
                var rootNodes = new List<ApparatusTypeDTO>();
                // 第一遍：建立索引
                foreach (var node in source)
                {
                    nodeMap[node.value] = node;
                }

                // 第二遍：建立父子关系
                foreach (var node in source)
                {
                    if (node.parentId.HasValue && nodeMap.TryGetValue(node.parentId.Value, out var parent))
                    {
                        parent.children.Add(node);
                    }
                    else
                    {
                        // 没有parentId或父节点不存在时作为根节点
                        rootNodes.Add(node);
                    }
                }

                return rootNodes;
            }
        }


        /// <summary>
        /// 树状
        /// </summary>
        /// <returns></returns>
        private async Task LoadTreeDataAsync()
        {

            try
            {

                uiTreeView1.BeginUpdate();

                var url = "https://localhost:7224/api/ApparatusType/QueryApparatusTreeType";
                var json = await HttpClientHelper.ClientAsync("GET", url);
                var result = JsonConvert.DeserializeObject<Result<List<ApparatusTypeDTO>>>(json);
                //  result.Data= TreeConverter.BuildTree(result.Data);
                if (result?.Code == 200)
                {
                    // 添加虚拟根节点（根据业务需要）
                    var fullData = new List<ApparatusTypeDTO>
            {
                new ApparatusTypeDTO
                {
                    value = 0,
                    label = "所有分类",
                    children = TreeConverter.BuildTree(result.Data)
                }
            };

                    uiTreeView1.Nodes.Clear();
                    uiTreeView1.Nodes.AddRange(ConvertToSunnyNodes(fullData));
                    uiTreeView1.ExpandAll();
                }
            }
            finally
            {
                uiTreeView1.EndUpdate();
            }
        }


        /// <summary>
        /// // SunnyUI树节点转换方法
        /// </summary>
        /// <param name="treeData"></param>
        /// <returns></returns>
        private TreeNode[] ConvertToSunnyNodes(List<ApparatusTypeDTO> treeData)
        {
            var nodes = new List<TreeNode>();

            foreach (var item in treeData)
            {
                var node = new TreeNode
                {
                    Text = item.label,
                    Tag = item.value, // 存储分类ID用于后续查询
                    ForeColor = Color.FromArgb(72, 72, 72), // 深灰色字体
                    //NodeStyle = UINodeStyle.CheckBox // 带复选框的节点样式
                };

                // 递归添加子节点
                if (item.children?.Count > 0)
                {
                    node.Nodes.AddRange(ConvertToSunnyNodes(item.children));
                }

                nodes.Add(node);
            }

            return nodes.ToArray();
        }

        private void QuerySterilizationForm_Load(object sender, EventArgs e)
        {

        }

        private void uiDataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            using (AddQueryForm addForm = new AddQueryForm())
            {
                if (addForm.ShowDialog() == DialogResult.OK)
                {
                    Refresh(); // 操作成功后刷新
                }
            }
        }

        private void uiLedLabel1_Click(object sender, EventArgs e)
        {

        }

        private void uiTreeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //AddQueryTypeForm addQueryTypeForm = new AddQueryTypeForm();
            //addQueryTypeForm.ShowDialog();//跳转
        }

        private void uiLabel2_Click(object sender, EventArgs e)
        {

        }

        private async void uiButton1_Click(object sender, EventArgs e)
        {
     
            using (AddQueryForm add = new AddQueryForm())
            {
                if (add.ShowDialog() == DialogResult.OK)
                {
                    // 获取当前筛选条件
                    string currentNo = uiTextBox1.Text.Trim();
                    string currentName = uiTextBox2.Text.Trim();

                    // 带条件刷新数据
                    await LoadDataAsync(currentNo, currentName);
                }
            }
        }

        private void uiSymbolButton1_Click(object sender, EventArgs e)
        {

        }

        private void QuerySterilizationForm_Initialize(object sender, EventArgs e)
        {

        }

        private async void uiButton2_Click(object sender, EventArgs e)
        {

            // 获取输入条件
            string apparatusNo = uiTextBox1.Text.Trim();
            string apparatusName = uiTextBox2.Text.Trim();

            try
            {
                await LoadDataAsync(apparatusNo, apparatusName);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询异常：{ex.Message}");
            }

        }


        public async void Inquire()
        {

        }

        private void uiTextBox1_TextChanged(object sender, EventArgs e)
        {

        }


        private void uiTextBox3_TextChanged(object sender, EventArgs e)
        {

        }

        private void uiCheckBox1_CheckedChanged(object sender, EventArgs e)
        {

        }

        private async void uiButton3_Click(object sender, EventArgs e)
        {

        }

        private void uiLabel3_Click(object sender, EventArgs e)
        {

        }

        private async void uiButton4_Click(object sender, EventArgs e)
        {      // 获取输入条件
            string apparatusNo = " ";
            string apparatusName = " ";

            try
            {
                await LoadDataAsync(apparatusNo, apparatusName);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"查询异常：{ex.Message}");
            }

        }





    
    
                #region 操作 修改
                /// <summary>
                /// 表格的重绘事件 DataGridViewCellPaintingEventArgs
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void uiDataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)//重绘“操作列”,使其有三个按钮
                {
                    //var a=e as DataGridViewCellPaintingEventArgs;
                    //   MessageBox.Show("重绘");
                    if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
                    {
                        //
                        if (this.uiDataGridView1.Columns[e.ColumnIndex].HeaderText == "操作" && this.uiDataGridView1.Rows[e.RowIndex].Cells["apparatusId"].Value != null)
                        {

                            //  MessageBox.Show("重绘333333333");
                            StringFormat sf = StringFormat.GenericDefault.Clone() as StringFormat;//设置重绘入单元格的字体样式
                            sf.FormatFlags = StringFormatFlags.DisplayFormatControl;
                            sf.Alignment = StringAlignment.Center;
                            sf.LineAlignment = StringAlignment.Center;
                            sf.Trimming = StringTrimming.EllipsisCharacter;

                            e.PaintBackground(e.CellBounds, false);//重绘边框

                            //设置要写入字体的大小
                            System.Drawing.Font myFont = new System.Drawing.Font("微软雅黑", 10F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(134)));

                            SizeF sizeMod = e.Graphics.MeasureString("编辑", myFont);
                            SizeF sizeDel = e.Graphics.MeasureString("删除", myFont);

                            float fMod = sizeMod.Width / (sizeDel.Width + sizeMod.Width);
                            float fDel = sizeDel.Width / (sizeDel.Width + sizeMod.Width);


                            //设置每个“按钮的边界”
                            RectangleF rectMod = new RectangleF(e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Width * fMod, e.CellBounds.Height);
                            //RectangleF rectMod = new RectangleF(rectPrint.Right, e.CellBounds.Top, e.CellBounds.Width * fMod, e.CellBounds.Height);
                            RectangleF rectDel = new RectangleF(rectMod.Right, e.CellBounds.Top, e.CellBounds.Width * fDel, e.CellBounds.Height);

                            Graphics grfx = CreateGraphics();
                            Color colorUse = Color.FromArgb(51, 136, 255);
                            Color colorPrint = Color.FromArgb(51, 136, 255);

                            e.Graphics.DrawString("编辑", myFont, new SolidBrush(colorUse), rectMod, sf);
                            e.Graphics.DrawString("删除", myFont, new SolidBrush(colorPrint), rectDel, sf); //绘制“按钮”
                            e.Handled = true;
                        }
                    }
                }
                /// <summary>
                /// 单元格点击事件
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private async void uiDataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
                {

                    try
                    {
                        if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
                        {
                            //  MessageBox.Show("重绘1111");

                            Point curPosition = e.Location;//当前鼠标在当前单元格中的坐标
                            if (this.uiDataGridView1.Columns[e.ColumnIndex].HeaderText == "操作" && uiDataGridView1.Rows[e.RowIndex].Cells["apparatusId"].Value != null)
                            {

                                Graphics g = this.uiDataGridView1.CreateGraphics();
                                System.Drawing.Font myFont = new System.Drawing.Font("微软雅黑", 10F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
                                //bool isPrintshow = (bool)(this.uiDataGridView1.Rows[e.RowIndex].Cells["isPrintshow"].Value);
                                //var isUse = (bool)this.uiDataGridView1.Rows[e.RowIndex].Cells["isUse"].Value;
                                //var isUseStr = !isUse && isPrintshow ? "已生单" : "生单";

                                //SizeF sizeprint = g.MeasureString(isUseStr, myFont);
                                SizeF sizeMod = g.MeasureString("编辑", myFont);
                                SizeF sizeDel = g.MeasureString("删除", myFont);

                                Rectangle rectTotal = new Rectangle(0, 0, this.uiDataGridView1.Columns[e.ColumnIndex].Width, this.uiDataGridView1.Rows[e.RowIndex].Height);
                                RectangleF rectDel;
                                //RectangleF rectMod;
                                RectangleF rectMod;

                                float fDel = sizeDel.Width / (sizeDel.Width + sizeMod.Width);
                                //float fMod = sizeMod.Width / (sizeDel.Width + sizeMod.Width + sizeprint.Width);
                                float fMod = sizeMod.Width / (sizeDel.Width + sizeMod.Width);

                                rectMod = new RectangleF(rectTotal.Left, rectTotal.Top, rectTotal.Width * fMod, rectTotal.Height);
                                //rectMod = new RectangleF(rectPrint.Right, rectTotal.Top, rectTotal.Width * fMod, rectTotal.Height);
                                rectDel = new RectangleF(rectMod.Right, rectTotal.Top, rectTotal.Width * fDel, rectTotal.Height);
                                //rectMod = new RectangleF(0, 0, 0, 0);

                                //判断当前鼠标在哪个“按钮”范围内
                                if (rectMod.Contains(curPosition))//编辑
                                {

                                    // 获取主键 ApparatusId
                                    string apparatusId = uiDataGridView1.Rows[e.RowIndex].Cells["apparatusId"].Value.ToString();

                                    // 传递给编辑窗体（假设窗体构造函数接收参数）
                                    EditapparatusForm editForm = new EditapparatusForm(apparatusId);
                                    editForm.ShowDialog();

                                    // 可选：刷新数据
                                    await LoadDataAsync();

                                    /*          //打开新的form窗体  
                                              EditapparatusForm add = new EditapparatusForm();
                                              add.ShowDialog();//跳转*/

                                }
                                else if (rectDel.Contains(curPosition))//删除
                                {

                                    var apparatusId = this.uiDataGridView1.Rows[e.RowIndex].Cells["apparatusId"].Value.ToString();//第一种:方式请求获取dataview表中的唯一流水号ID
                                    var pdata = new { ApparatusId = apparatusId };
                                    var pdataStr = JsonConvert.SerializeObject(pdata);
                                    HttpContent httpContent = new StringContent(pdataStr, Encoding.UTF8, "application/json");
                                    var json = await HttpClientHelper.ClientAsync("put", "https://localhost:7286/api/Apparatus/DelApparatus", true, httpContent);
                                    ApparaData result = JsonConvert.DeserializeObject<ApparaData>(json);

                                    if (result != null)
                                    {
                                        MessageBox.Show("删除成功");
                                        string currentApparatusNo = uiTextBox1.Text.Trim();
                                        string currentApparatusName = uiTextBox2.Text.Trim();
                                        await LoadDataAsync(currentApparatusNo, currentApparatusName);

                                    }


                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }

                /// <summary>
                /// 在按钮上鼠标箭头变成小手样式
                /// </summary>
                /// <param name="sender"></param>
                /// <param name="e"></param>
                private void uiDataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
                {
                    if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
                    {
                        Point curPosition = e.Location;//当前鼠标在当前单元格中的坐标
                        if (this.uiDataGridView1.Columns[e.ColumnIndex].Name == "操作")
                        {
                            this.Cursor = Cursors.Hand;
                            //解决绘图时画面闪烁
                            SetStyle(ControlStyles.UserPaint, true);
                            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
                            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲
                                                                        //   MessageBox.Show("鼠标移动");
                        }
                    }
                }
            }
        }
 


#endregion        

